<template>
  <div>
    <el-card shadow="never">
      <header-title title="追溯信息查询"></header-title>
    </el-card>
    <el-card shadow="never">
      选择追溯日期：
      <el-date-picker
        size="small" style="margin: 0 0 20px 0;"
        @change="changePurchaseDateValue"
        v-model="purchaseDateValue"
        :picker-options="pickerOptionsdate"
        type="date"
        placeholder="选择日">
      </el-date-picker>
      <el-tabs v-model="currentProduct.name" @tab-click="handleClick">
        <el-tab-pane v-for="item in products" :key="item.name" :label="item.label" :name="item.name">
        </el-tab-pane>
      </el-tabs>
      <el-form style="width:460px" label-width="100px" :model="upperReaches">
            <el-form-item :inline="true" label="供应商编码">
              <el-input v-model="upperReaches.supplyMarketCode" readonly></el-input>
            </el-form-item>
            <el-form-item :inline="true" label="供应商名称">
              <el-input v-model="upperReaches.supplyMarketName" readonly></el-input>
            </el-form-item>
          </el-form>
    </el-card>

    <el-card shadow="never">
      <div style="margin: 20px 0;">
        <el-row>
          <el-col  :span="2">
            <header-title title="购买人"></header-title>
          </el-col>
          <el-col :offset="20" :span="2">
            <el-button v-if="currentProduct.hasRecall == false" size="small" type="primary" @click="showNewRecallDialog">发起召回</el-button>
          </el-col>
        </el-row>
            <el-table :data="meatData" v-loading="loading" style="width: 100%;margin: 15px 0 25px;">
              <el-table-column prop="orderNumber" label="订单编号"></el-table-column>
              <el-table-column prop="nickName" label="昵称"></el-table-column>
              <el-table-column prop="weight" label="重量（KG）"></el-table-column>
              <el-table-column prop="total" label="金额（元）"></el-table-column>
              <el-table-column prop="consumeDate" label="购买时间"></el-table-column>
              <el-table-column v-if="currentProduct.hasRecall" prop="pushStatus" label="推送状态"></el-table-column>
              <div slot="empty"><img src="../../assets/blank_tip_page/blank_tip_page.png" alt=""></div>
            </el-table>
            <el-pagination
              :page-size="meatPage.perPage"
              :current-page="meatPage.page"
              :total="meatPage.total"
              @current-change="changeMeatPage"
              style="margin-top: 15px;"
              background
              layout="prev, pager, next"
            ></el-pagination>
          </div>
    </el-card>
    <el-dialog width="400px" title="召回信息" :visible.sync="dialogFormVisible">
  <el-form :model="newRecallModel">
    <el-form-item>
      <el-input type="textarea" :rows="6" v-model="newRecallModel.pushMessage" autocomplete="off"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitNewRecall">确 定</el-button>
  </div>
</el-dialog>
  </div>
</template>
<script>
import HeaderTitle from "@/components/HeaderTitle"
import CountUp from '@/components/CountUp/index'
import CardItem from '@/components/CardItem/index.vue'
import MySelect from "@/components/MySelect"
import { formatDate, formatDate2, isNil } from '@/utils'
export default {
  name: 'PurchaseInfo',
  components: {
     HeaderTitle,
     CountUp,
     CardItem,
     MySelect
  },
  data(){
    return {
      purchaseDateValue: formatDate(new Date()), // 选择购进日期 日
      // 选择日 的限制
      pickerOptionsdate: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6
        }
      },
      currentProduct: {},
      products: [],
      meatData: [],
      meatPage: {
        perPage: 10, // 每页显示10条
        page: 1, // 当前页
        total: 0
      },
      businessId: -1,
      loading: false,
      upperReaches:{},
      newRecallModel:{},
      dialogFormVisible: false
    }
  },
  watch: {
    '$store.state.app.marketId'(val, oldVal){
    }
  },
  mounted(){
    this.businessId = this.$route.params['businessId']
    // this.businessId = 87
    // this.purchaseDateValue = '2019-06-24' // 测试用上线需要删除
    this.fetchProducts(this.businessId, "", this.purchaseDateValue)
  },
  methods:{
    defaultValue (value, defaultValue) {
      if (isNil(value)) {
        return defaultValue
      }
      return value
    },
    // 改变日期
    changePurchaseDateValue(date){
      this.fetchProducts(this.businessId, this.currentProduct.name, this.purchaseDateValue)
    },

    fetchProducts(businessId, productName, saleDate){
      this.loading = true
      this.$store.dispatch("trace/fetchProducts", {businessId, productName, saleDate}).then(
        data => {
          this.loading = false
          this.products = []

          if (data.length < 1){
            return
          }

          for(let productInfo of data) {

            let tabName = productInfo.productName
            let tabLabel = productInfo.productName
            if (productInfo.hasRecall){
              tabLabel = tabLabel += "(已发起召回)"
            }

            this.products.push({name:tabName, label:tabLabel, hasRecall: productInfo.hasRecall})
          }

          this.currentProduct = this.products[0]

          this.fetchUpperReaches(businessId, this.currentProduct.name, saleDate)

          if(this.currentProduct.hasRecall){
            this.fetchRecalls(businessId, this.currentProduct.name, saleDate, this.meatPage.perPage, 1)
          } else {
            this.fetchBuyers(businessId, this.currentProduct.name, saleDate, this.meatPage.perPage, 1)
          }
        }
      ).catch(err => {
        console.log("fetchProducts err", err)
        this.loading = false
      })
    },
    // 所有Meat列表
    fetchBuyers(businessId, productName, saleDate, perPage, page){
      this.$store.dispatch('trace/fetchBuyers',{businessId, productName, saleDate, perPage, page}).then(
        data => {
          console.log("zhe li", 123)
          this.loading = false
          this.meatData = []
          for (let item of data.items) {
            if(item.nickName == ""){
              item.nickName = item.wxOpenId
              item.consumeDate = item.endDate
              item.weight = Math.round(item.weight/1000)
            }
            this.meatData.push(item)
          }

          this.meatPage.total = data.total
        }
      ).catch(err => {
        this.loading = false
        this.meatData = []
        this.meatPage.total = 0
      })
    },

    fetchRecalls(businessId, productName, saleDate, perPage, page){
      this.$store.dispatch('trace/fetchRecalls',{businessId, productName, saleDate, perPage, page}).then(
        data => {
          this.loading = false
          this.meatData = []
          for (let item of data.items) {
            if(item.nickName == ""){
              item.nickName = item.wxOpenId
              item.weight = item.weight/1000
              item.total = item.total/100
              switch (item.pushStatus) {
                case 0:
                  item.pushStatus = "等待推送"
                  break
                case 1:
                  item.pushStatus = "推送成功"
                  break
                case 2:
                  item.pushStatus = "推送失败"
                  break
              }
            }
            this.meatData.push(item)
          }

          this.meatPage.total = data.total
        }
      ).catch(err => {
        this.loading = false
        this.meatData = []
        this.meatPage.total = 0
      })
    },

    fetchUpperReaches(businessId, productName, saleDate){
      this.$store.dispatch('trace/fetchUpperReaches',{businessId, productName, saleDate}).then(
        data => {
          this.loading = false
          this.upperReaches = data
        }
      ).catch(err => {
        this.loading = false
      })
    },

    changeMeatPage(num){
      this.meatPage.page = num
      if(this.currentProduct.hasRecall){
            this.fetchRecalls(this.businessId, this.currentProduct.name, this.purchaseDateValue, this.meatPage.perPage, num)
          } else {
            this.fetchBuyers(this.businessId, this.currentProduct.name, this.purchaseDateValue, this.meatPage.perPage, num)
          }
    },

    handleClick(tab, event) {
      this.loading = true
      this.meatModal = {}
      this.productsPushArr = []

      for(let product of this.products) {
        if(product.name == tab.name) {
          this.currentProduct = product
          break
        }
      }
      this.fetchBuyers(this.businessId, this.currentProduct.name, this.purchaseDateValue, this.meatPage.perPage, 1)
    },

    showNewRecallDialog(){
      this.newRecallModel = {}
      let message = "您好，您于 " + this.purchaseDateValue + " 购买的 " + this.currentProduct.name + " 发现安全隐患,请勿食用!"
      this.newRecallModel.pushMessage = message
      this.dialogFormVisible = true
    },

    submitNewRecall() {
      let pushMessage = this.newRecallModel.pushMessage
      let businessId = this.businessId
      let productName = this.currentProduct.name
      let saleDate = this.purchaseDateValue
      this.$store.dispatch('trace/addRecall',{businessId, productName, saleDate, pushMessage}).then(
        data => {
          this.dialogFormVisible = false
          this.fetchRecalls(businessId, productName, saleDate, this.meatPage.perPage, this.meatPage.page)
        }
      ).catch(err => {

      })
    }
  }
}
</script>

<style lang="scss" scoped>
  /deep/ .el-table__empty-text{
    width: 100%;
  }
#detail-dialog{
  .ptitle{
    color: #00CBE4;
    font-size: 16px;
  }
  .pnumber{
    margin: 15px 10px;
    font-size: 14px;
  }
  /deep/.el-dialog__body {
    padding: 0px 20px 30px;
    color: #606266;
    font-size: 14px;
  }
  /deep/.el-card__header {
    padding: 10px 20px 0;
    border-bottom: 1px solid #EBEEF5;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
  }
}
</style>
